package stc.skymobi.netty.handler.codec.memcached;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import stc.skymobi.netty.handler.codec.memcached.bean.request.BinaryRequestHeader;
import stc.skymobi.util.ByteUtils;

import java.io.UnsupportedEncodingException;

public class MemcachedRequestEncoder extends MessageToByteEncoder {
    private static Logger logger = LoggerFactory.getLogger(MemcachedRequestEncoder.class);

    @Override
    public void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
        if (isHandled(msg)) {
            byte[] result = encode(msg);
            if (logger.isDebugEnabled()) {
                logger.debug("send request:{}", ByteUtils.bytesAsHexString(result, 128));
            }
            out.writeBytes(result);
        }
    }

    /**
     * Detemine of object can be natively serialized by this class.
     *
     * @param value Object to test.
     * @return true/false
     */
    public static boolean isHandled(Object value) {

        return value instanceof BinaryRequestHeader;
    }

    /**
     * Encodes supported types
     *
     * @param value Object to encode.
     * @return byte array
     * @throws java.io.UnsupportedEncodingException
     *          If fail to encode.
     */
    public byte[] encode(Object value) throws UnsupportedEncodingException {
        return MemcachedNativeCodec.getBeanCodec().encode(MemcachedNativeCodec.getBeanCodec().getEncContextFactory().createEncContext(
                value, value.getClass(), null));
    }
}
